package com.ah.service;

import com.ah.common.result.R;
import com.ah.common.service.IAccountService;
import com.ah.entity.TAccount;
import com.ah.mapper.AccountMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

@DubboService
public class AccountServiceImpl implements IAccountService {
    @Autowired
    private AccountMapper accountMapper;


    @Override
    public R debit(String userId, Integer money) {
        LambdaQueryWrapper<TAccount> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TAccount::getUserId,userId);
        TAccount account = accountMapper.selectOne(queryWrapper);

        if(Objects.isNull(account)){
            return R.error("用户不存在");
        }

        if(account.getMoney() < money){
            return R.error("余额不足");
        }
        //扣减余额
        account.setMoney(account.getMoney() - money);

        //修改数据库
        int row = accountMapper.updateById(account);
        if(row == 1){
            return R.success();
        }

        return R.error("扣减余额失败,服务异常");
    }
}
